package com.fivestar.pmanager.core.formatter;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import org.springframework.format.Formatter;

public class DateFormatter implements Formatter<Date>
{
    private List<String> formatPatterns;
    
    public DateFormatter()
    {
        
    }
    
    public DateFormatter(List<String> formatPatterns)
    {
        this.formatPatterns = formatPatterns;
        formatPatterns.add(null);
    }
    
    
    @Override
    public String print(Date param, Locale paramLocale)
    {
        String dateStr = "";
        SimpleDateFormat sdf = new SimpleDateFormat();
        for(String dateStyle : formatPatterns)
        {
            try
            {
                sdf.applyPattern(dateStyle);
                dateStr = sdf.format(param);
                break;
            }
            catch(Exception e)
            {
                continue;
            }
        }
        return dateStr;
    }

    @Override
    public Date parse(String paramString, Locale paramLocale)
    {
        
        Date date = null;
        SimpleDateFormat sdf = new SimpleDateFormat();
        
        for(String dateStyle : formatPatterns)
        {
            try
            {
                if(dateStyle != null)
                {
                    sdf.applyPattern(dateStyle);
                }
                date = sdf.parse(paramString);
                break;
            }
            catch(Exception e)
            {
                continue;
            }
        }
        return date;
        
    }

}
